package com.zhai.domain.strategy.service.rule.chain.impl;

import com.zhai.domain.strategy.repository.IStrategyRepository;
import com.zhai.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.zhai.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.zhai.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Description: 黑名单责任链节点
 * @ClassName: BlackListLogicChain
 * @Author: zhaiyongxin
 * @Date: 2025/1/9 14:35
 * @Version: 1.0
 */
@Slf4j
@Component("rule_blacklist")
public class BlackListLogicChain extends AbstractLogicChain {

    @Resource
    protected IStrategyRepository repository;

    /**
     * 责任链接口
     *
     * @param userId     用户id
     * @param strategyId 策略id
     * @return 奖品id
     */
    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-黑名单开始 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, this.ruleModel());
        // 如果存在黑名单规则，进行黑名单过滤操作：如果用户ID在黑名单列表，则返回黑名单奖品
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.valueOf(splitRuleValue[0]);
        String[] blackUserList = splitRuleValue[1].split(Constants.SPLIT);
        for (String blackUser : blackUserList) {
            if (userId.equals(blackUser)) {
                return DefaultChainFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .logicModel(ruleModel())
                        // 写入默认配置黑名单奖品值 0.01 ~ 1 积分，也可以配置到数据库表中
                        .awardRuleValue("0.01,1")
                        .build();
            }
        }
        // 过滤其他责任链
        log.info("抽奖责任链-黑名单放行 userId: {} strategyId: {} ruleModel: {}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }
}
